﻿using System.Globalization;
using System.Text;

namespace IntelligentDataCollection.Tool
{
    public class Untils
    {
        // 字符转为ASCII码
        public static byte[] StringToASCII(string strs)
        {
            char[] charBuf = strs.ToArray();// 将字符串转为字符数组
            ASCIIEncoding aSCIIEncoding = new ASCIIEncoding();
            byte[] bytes = new byte[charBuf.Length];// 定义发送数据缓冲区
            bytes = aSCIIEncoding.GetBytes(charBuf);
            return bytes;
        }
        public static void WriteData(string content)
        {
            try
            {
                StringBuilder DataColumn = new StringBuilder();
                StringBuilder DataLine = new StringBuilder();
                string strT = DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Hour.ToString() + "-" + DateTime.Now.Minute.ToString() + "-" + DateTime.Now.Second.ToString() + "-" + DateTime.Now.Millisecond.ToString();

                //列标题
                DataColumn.Append("描述,");
                //行数据
                DataLine.Append(content + ",");
                string path = AppDomain.CurrentDomain.BaseDirectory + @"\log\" + DateTime.Now.ToString("yyyy-MM-dd") + ".CSV";

                if (System.IO.File.Exists(path) == false)
                {
                    System.IO.StreamWriter stream = new System.IO.StreamWriter(path, false, Encoding.UTF8);
                    stream.WriteLine(DataColumn);
                    stream.WriteLine(DataLine);
                    stream.Flush();
                    stream.Close();
                    stream.Dispose();
                }
                else
                {
                    System.IO.StreamWriter stream = new System.IO.StreamWriter(path, true, Encoding.UTF8);
                    stream.WriteLine(DataLine);
                    stream.Flush();
                    stream.Close();
                    stream.Dispose();
                }
            }
            catch (Exception ex)
            {

            }
        }
        static ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
        // 记录运行时间
        public static void Log(string content)
        {
            try
            {
                LogWriteLock.EnterWriteLock();
                string path = AppDomain.CurrentDomain.BaseDirectory + @"\log\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                File.AppendAllText(path, content + Environment.NewLine);
            }
            catch (Exception e)
            {
                Error(DateTime.Now + "  :记录日志出现的异常: " + e.Message);
            }
            finally
            {
                LogWriteLock.ExitWriteLock();
            }
        }
        public static void Error(string content)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + @"\log\error.txt";
            File.AppendAllText(path, content + Environment.NewLine);
        }
        // 读取文本文件内容到数组中
        public static string[] loadArrayFromTxt(string filename)
        {
            string[] lines = File.ReadAllLines(filename);
            List<string> lists = new List<string>();
            foreach (string line in lines)
            {
                if (!string.IsNullOrWhiteSpace(line))
                {
                    int index = line.IndexOf("//");
                    if (index != -1)
                    {
                        if (line.Substring(0, index).Trim() != "")
                        {
                            lists.Add(line.Substring(0, index).Trim());
                        }
                    }
                    else
                    {
                        lists.Add(line.Trim());
                        //Console.WriteLine(string.IsNullOrWhiteSpace(line.Trim()));
                    }
                    Console.WriteLine(line);
                }
            }
            return lists.ToArray();
        }
        public static Dictionary<string, string> LoadDataSetFromFile(string path)
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();
            string[] allData = new string[0];
            // 获取文件下的所有文件
            string[] files = Directory.GetFiles(path + @"\");
            for (int i = 0; i < files.Length; i++)
            {
                if (files[i].Contains("UT-5512"))
                { // 处理5512的数据
                    foreach (string line in File.ReadAllLines(files[i]))
                    {
                        string key = line.Split(':')[0];
                        string value = line.Split(':')[1];
                        dict.Add(key, value);
                    }
                }
                else if (files[i].Contains("UT-5524A"))
                {
                    foreach (string line in File.ReadAllLines(files[i]))
                    {
                        string key = line.Split(':')[0];
                        string value = line.Split(':')[1];
                        dict.Add(key, value);
                    }
                }
                allData = allData.Concat(loadArrayFromTxt(files[i])).ToArray(); // 一个文件
            }
            return dict;
        }
        public static byte[] ToBytes(string str)
        {
            List<byte> result = new List<byte>();
            if (str.Contains(","))
            {
                string[] strs = str.Trim().Split(',');
                foreach (string s in strs)
                {
                    result.Add(Convert.ToByte(s.Trim(), 16));
                }
            }
            else if (str.Contains(" "))
            {
                string[] strs = str.Trim().Split(' ');
                foreach (string s in strs)
                {
                    result.Add(Convert.ToByte(s.Trim(), 16));
                }
            }
            else
            {
                result.Add(Convert.ToByte(str, 16));
            }
            return result.ToArray();
        }
        public static string ToHexs(byte[] data, char spit = ',')
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sb.Append(data[i].ToString("X2"));
                sb.Append(spit);
            }
            string str = sb.ToString();
            return str = str.Substring(0, str.Length - 1);
        }
        public static float intStringToFloat(byte[] intBuffer)
        {
            byte[] bytes = new byte[4] { intBuffer[3], intBuffer[2], intBuffer[1], intBuffer[0] };
            float val = BitConverter.ToSingle(bytes, 0);
            //decimal dData = Convert.ToDecimal(Decimal.Parse(val.ToString(), System.Globalization.NumberStyles.Float));
            return val;
        }
        public static double intStringToDouble(byte[] intBuffer)
        {
            byte[] bytes = new byte[2] { intBuffer[1], intBuffer[0] };
            double val = BitConverter.ToDouble(bytes, 0);
            //decimal dData = Convert.ToDecimal(Decimal.Parse(val.ToString(), System.Globalization.NumberStyles.Float));
            return val;
        }
        public static double intStringToDouble1(byte[] data)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sb.Append(data[i].ToString("X2"));
            }
            return Convert.ToInt32(sb.ToString(), 16);
        }
        public static float intStringToFloat1(string strData)
        {

            string[] strs = strData.Split(',');
            byte[] intBuffer = new byte[strs.Length];
            for (int i = 0; i < strs.Length; i++)
            {
                intBuffer[i] = (byte)Convert.ToInt32(strs[i], 16);
            }

            byte[] bytes = new byte[4] { intBuffer[3], intBuffer[2], intBuffer[1], intBuffer[0] };
            float val = BitConverter.ToSingle(bytes, 0);
            //decimal dData = Convert.ToDecimal(Decimal.Parse(val.ToString(), System.Globalization.NumberStyles.Float));
            return val;
        }
        public static double intStringToDouble2(string strData)
        {
            string[] data = strData.Split(',');

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sb.Append(data[i]);
            }
            return Convert.ToInt32(sb.ToString(), 16);
        }
        public static bool compareBytes(byte[] source, byte[] dest)
        {
            if (source.Length < dest.Length) return false;
            for (int i = 0; i < dest.Length; i++)
            {
                if (source[i] != dest[i]) return false;
            }
            return true;
        }
        public static byte[] ConvertDoubleToByteArray(int d)
        {

            return BitConverter.GetBytes(d);

        }
        public static double ConvertToDouble(byte[] data)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sb.Append(data[i].ToString("X2"));
            }
            return Convert.ToInt32(sb.ToString(), 16);
        }
        public static string ReplaceCommonEscapeSequences(string s)
        {
            return s.Replace("\\n", "\n").Replace("\\r", "\r");
        }

        public static string InsertCommonEscapeSequences(string s)
        {
            return s.Replace("\n", "\\n").Replace("\r", "\\r");
        }

        public static int intStringToInt(byte[] intBuffer)
        {
            byte[] bytes = new byte[2] { intBuffer[1], intBuffer[0] };
            int val = BitConverter.ToInt16(bytes, 0);
            //decimal dData = Convert.ToDecimal(Decimal.Parse(val.ToString(), System.Globalization.NumberStyles.Float));
            return val;
        }
        public static int ByteArrarToInt32(byte[] intBuffer)
        {
            byte[] bytes = new byte[2] { intBuffer[2], intBuffer[3] };
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                sb.Append(bytes[i].ToString("X2"));
            }

            Int32 a = (((intBuffer[1] << 16 | int.Parse(sb.ToString(), NumberStyles.HexNumber)) << 8) >> 8);
            //decimal dData = Convert.ToDecimal(Decimal.Parse(val.ToString(), System.Globalization.NumberStyles.Float));
            return a;
        }

        // crc校验和
        public static ushort crc_16(byte[] data)
        {
            uint IX, IY;
            ushort crc = 0xFFFF;//set all 1

            int len = data.Length;
            if (len <= 0)
                crc = 0;
            else
            {
                len--;
                for (IX = 0; IX <= len; IX++)
                {
                    crc = (ushort)(crc ^ (data[IX]));
                    for (IY = 0; IY <= 7; IY++)
                    {
                        if ((crc & 1) != 0)
                            crc = (ushort)((crc >> 1) ^ 0xA001);
                        else
                            crc = (ushort)(crc >> 1); //
                    }
                }
            }

            byte buf1 = (byte)((crc & 0xff00) >> 8);//高位置
            byte buf2 = (byte)(crc & 0x00ff); //低位置

            crc = (ushort)(buf1 << 8);
            crc += buf2;
            return crc;
        }

        // 字节数组转换为16进制
        public static string BytesToHexs(byte[] data)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sb.Append(data[i].ToString("X2"));
            }
            return sb.ToString();
        }

        //crc校验
        public static byte[] Crc18(byte[] buffer, int start = 0, int len = 0)
        {
            if (buffer == null || buffer.Length == 0) return null;
            if (start < 0) return null;
            if (len == 0) len = buffer.Length - start;
            int length = start + len;
            if (length > buffer.Length) return null;
            ushort crc = 0xFFFF;// Initial value
            for (int i = start; i < length; i++)
            {
                crc ^= buffer[i];
                for (int j = 0; j < 8; j++)
                {
                    if ((crc & 1) > 0)
                        crc = (ushort)((crc >> 1) ^ 0xA001);// 0xA001 = reverse 0x8005
                    else
                        crc = (ushort)(crc >> 1);
                }
            }
            byte[] ret = BitConverter.GetBytes(crc);
            Array.Reverse(ret);
            return ret;
        }

        public static byte[] toBytes(int number)
        {
            byte[] bytes = new byte[2];
            bytes[0] = (byte)number;
            bytes[1] = (byte)(number >> 8);
            return bytes;
        }
    }
}
